﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;

namespace Invest.DataBaseUpdater.Core
{
  public  class LogProcessor:BaseProcessor
    {
      public LogProcessor(SqlConnection connection) : base(connection)
      {
      }

      public void InsertUpdateData()
      {
          OpenConnection();
          var executedFiles = new List<string>();
          try
          {
              executedFiles.AddRange(GetListExecutedFiles());
          }
          catch
          {
              executedFiles = new List<string>();
          }

          var scriptFiles = Directory.GetFiles("DataBaseUpdateScripts", "*.sql", SearchOption.AllDirectories).ToList().Except(executedFiles).ToList();

          foreach (var scriptFile in scriptFiles)
          {
              string sqlQuery;
              string sqlHeader;
              bool skipTransaction;

              ReadSqlFromFile(scriptFile, out sqlQuery, out sqlHeader, out skipTransaction);

              if (string.IsNullOrWhiteSpace(sqlQuery))
              {
                  continue;
              }
              UpdateRefactorLog(scriptFile, sqlHeader);
          }
      }
      public void UpdateRefactorLog(string fileName, string description)
      {
          const string query = "INSERT INTO [System].[RefactorLog] ([file-name], [description], [runing-date]) VALUES (@filename,@description,@date)";
          var command = new SqlCommand(query, Connection);
          command.Parameters.AddWithValue("@filename", fileName);
          command.Parameters.AddWithValue("@description", description);
          command.Parameters.AddWithValue("@date", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
          command.ExecuteNonQuery();
      }


    }
}
